package com.yunfei.common.auto.cratePage;


import com.yunfei.common.auto.GeneratorBase;
import com.yunfei.common.auto.util.CapitalizeUtil;
import com.yunfei.common.auto.util.DbInfoUtil;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.List;
import java.util.Map;

/**
 * 自动创建表单提交需要的js文件
 * @author  贤云
 *
 */
public class GeneratorFormJs extends GeneratorBase {
    public static Connection getConnection(){
        Connection conn = null;
        try {
            Class.forName(GeneratorBase.DRIVER);
            String url = GeneratorBase.URL;
            String user = GeneratorBase.NAME;
            String pass = GeneratorBase.PASS;
            conn = DriverManager.getConnection(url,user,pass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static void main(String[] args){
        GeneratorFormJs generatorInitPageDB=new GeneratorFormJs();
        generatorInitPageDB.generatorInitPage();
    }
    public  void generatorInitPage(){
        Connection conn=getConnection();
        String sql="select * from "+tablename;
        PreparedStatement stmt;
        String content="";
        try {
            stmt = conn.prepareStatement(sql);
            ResultSet rs=stmt.executeQuery(sql);
            //ResultSetMetaData data=rs.getMetaData();
            String driver = GeneratorBase.DRIVER;
            String url = GeneratorBase.URL;
            String user = GeneratorBase.NAME;
            String pwd =GeneratorBase.PASS;
            //String table = "FZ_USER_T";
            GeneratorBase generatorBase=new GeneratorBase();
            String table = generatorBase.tablename;
            List<Map<String,Object>> data= DbInfoUtil.getTableInfo(driver,url,user,pwd,table);
            DatabaseMetaData dbmd=conn.getMetaData();
            ResultSet  resultSet  = dbmd.getTables(null, "%", tablename, new String[] { "TABLE" });

            while(rs.next()){
                int columnCount=data.size();
                for(int i = 1 ; i<columnCount ; i++){
                    //获得所有列的数目及实际列数
                    //获得指定列的列名
                    String columnName = data.get(i).get("COLUMN_NAME").toString();
                    String columnRemark=data.get(i).get("columnRemark").toString();
                    String columnRemarkAll=columnRemark;
                    //获得指定列的列值
                    String columnValue = rs.getString(i);

                    String columnLabel= CapitalizeUtil.initcap(columnName.toLowerCase());

                    //是否为空
                    int isNullable=Integer.parseInt(data.get(i).get("isNullable").toString());
                    boolean isFormElement=true;
                    isFormElement = !columnRemarkAll.contains("noListElement");
                    if(isFormElement){//去掉noListElement不在列表里面的列元素
                        boolean isNullableBoolean=false;
                        if(isNullable==1){
                            isNullableBoolean=true;
                        }
                        columnLabel=CapitalizeUtil.replaceUnderlineAndfirstToUpper(data.get(i).get("COLUMN_NAME").toString().toLowerCase(),"_","");//将数据库列转小写，去掉下划线并首字母大写

                        if(!content.contains(columnLabel)&&!columnRemarkAll.contains("isImage")){//非图片的内容处理
                            content+="\t\t\t\t\t\t{ display: '"+columnRemark+"', name: '"+columnLabel+"', width: '120' },\n";
                        }
                        if(!content.contains(columnLabel)&&columnRemarkAll.contains("isImage")){//图片的内容处理
                            content+="\t\t\t\t\t\t{ display: '"+columnRemark+"', name: '"+columnLabel+"', width: '200',rowHeight:60,render:function(r){\n" +
                                    "\t    \t    \t\t\tvar img=r.pic;\n" +
                                    "\t\t\t\t\t\t\tvar result=\"\";\n" +
                                    "\t\t\t\t\t\t\tvar divStr=\"\";\n" +
                                    "\t\t\t\t\t\t\tif(''!=img&&null!=img){\n" +
                                    "\t\t\t\t\t\t\t\tresult+='<div style=\"width: 50%;float: left\"><img src='+img+' style=\"width:100px;height:100px\" /></div>';\n" +
                                    "                                divStr=\"<div style='float: right;width: auto;width:46%;padding-left:5px'>\";\n" +
                                    "\t\t\t\t\t\t\t}else{\n" +
                                    "                                divStr=\"<div style='float: left;width: auto;width:100%;'>\";\n" +
                                    "                            }\n" +
                                    "\t\t\t\t\t\t\tresult+=divStr+\"</div>\";\n" +
                                    "\t\t\t\t\t\t\treturn result;\n" +
                                    "\t\t\t\t\t\t} },\n";
                        }
                    }
                }
            }
            /****************************************自动生成form.jsp页面 start******************************************************************************/

            try {
                String controlMapper=CapitalizeUtil.replaceUnderlineAndfirstToUpper(tablename.toLowerCase(),"_","");
                content=getInitPageContent(pageTitle, pageOutPath,content,controlMapper);
                File directory = new File("");
               // String outputPath = directory.getAbsolutePath()+ "/web/"+ pageOutPath+"/js/form.js";
                String outputPath = /*directory.getAbsolutePath()+ "/web/"+ */pagePath+"/js/form.js";
                File file=new File(outputPath);
                file.getParentFile().mkdirs();
                FileWriter fw = new FileWriter(outputPath);
                PrintWriter pw = new PrintWriter(fw);
                pw.println(content);
                pw.flush();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            /****************************************自动生成form.js页面 end******************************************************************************/
        } catch (SQLException e) {
            System.out.println("数据库连接失败");
        }
    }
    public static String parse(String all) {
        String comment = null;
        int index = all.indexOf("COMMENT='");
        if(index < 0) {
            return "";
        }
        comment = all.substring(index+9);
        comment = comment.substring(0,comment.length() - 1);
        return comment;
    }
    /**
     *生成表单提交页面
     * @param title 页面标题
     * @param path s9/v3/pastInvestmentCase 页面所在路径
     * @return
     */
    public static  String getInitPageContent(String title,String path,String autoCreateForm,String controlMapper){
        String content="";
        content="\tvar grid = null;//表格对象\n" +
                "\tvar m ; \t//弹出窗口对象\n" +
                "\t$(function(){\n" +
                "\t\t//查询产品信息列表\n" +
                "\t\tvar url = \"../"+controlMapper+"/findAllList.shtml\" ;\n" +
                "\t\tfindProjectInfoList(url);\n" +
                "\t\t\n" +
                "\t});\n" +
                "\tfunction findProjectInfoList(url){\n" +
                "\t\t   var pageSize=20;\n" +
                "\t       grid = $(\"#maingrid\").ligerGrid({\n" +
                "\t    \t    width:'100%',\n" +
                "\t    \t    height:'100%',\n" +
                "\t\t\t\theaderRowHeight:28,\n" +
                "\t\t\t\trowHeight:26,\n" +
                "\t\t\t\tcheckbox: false,\n" +
                "\t    \t\tcolumns: [\n" ;
                content+=autoCreateForm;
                content+="\t\t\t\t\t\t{ display: '操作', name: '',width:280,render:function(r){\n" +
                "                        \tvar html=\"\";\n" +
                "                        \thtml+=\"<a class='z-btn z-btn-flat' href='javascript:updateInitPage(\"+r.id+\")'><img class='icon003a4' src='../s9/res/img/icon000.png'>编辑</a>\";\n" +
                "                       \t\thtml+=\"&nbsp;\";\n" +
                "                        \thtml+=\"<a class='z-btn z-btn-flat' href='javascript:del(\"+r.id+\")'><img class='icon404a5' src='../s9/res/img/icon000.png'><b>删除</b></a>\";\n" +
                "                        \treturn html;\n" +
                "\t\t\t\t\t\t}}\n" +
                "\t          ], url:url, pageSize:20,rownumbers:true,pageParmName:\"curNo\",pagesizeParmName:\"curSize\"\n" +
                "               //grid的这个事件，一般来说对表格的二次加工，都是在这个事件里去处理\n" +
                "               ,onAfterShowData:function()\n" +
                "               {\n" +
                "                   $(\".l-grid-row-cell-inner\").css(\"height\",\"auto\"); //单元格高度自动化，撑开\n" +
                "                   var i=0;\n" +
                "                   $(\"tr\",\".l-grid2\",\"#recordgrid\").each(function ()\n" +
                "                   {\n" +
                "                       $($(\"tr\",\".l-grid1\",\"#maingrid\")[i]).css(\"height\",$(this).height()); //2个表格的tr高度一致\n" +
                "                       i++;\n" +
                "                   });\n" +
                "               },\n" +
                "               onAfterChangeColumnWidth:function()\n" +
                "               {\n" +
                "                   $(\".l-grid-row-cell-inner\").css(\"height\",\"auto\");\n" +
                "                   var i=0;\n" +
                "                   $(\"tr\",\".l-grid2\",\"#recordgrid\").each(function ()\n" +
                "                   {\n" +
                "                       $($(\"tr\",\".l-grid1\",\"#maingrid\")[i]).css(\"height\",$(this).height());\n" +
                "                       i++;\n" +
                "                   });\n" +
                "               }\n" +
                "\t\t\t });\n" +
                "            //grid.set({ newPage: 1});\n" +
                "\t      $(\"#pageloading\").hide();\n" +
                "\t}\n" +
                "\tfunction addInitPage() {\n" +
                "\t\tvar url= \"../"+controlMapper+"/form.shtml\" ;\n" +
                "\t\tm = $.ligerDialog.open({ url: url, height: 570,width:600, title:'添加"+title+"',isResize: true ,top:50,showMax:true,showToggle:true,showMin:true});\n" +
                "\t\t//window.location.href=url;\n" +
                "\t}\n" +
                "\tfunction updateInitPage(id) {\n" +
                "\t\tvar url= \"../"+controlMapper+"/form.shtml?id=\"+id ;\n" +
                "\t\tm = $.ligerDialog.open({ url: url, height: 570,width:600, title:'编辑"+title+"',isResize: true ,top:50,showMax:true,showToggle:true,showMin:true});\n" +
                "\t\t//window.location.href=url;\n" +
                "\t}\n" +
                "    function update(id) {\n" +
                "        var url= \"../"+controlMapper+"/form.shtml?id=\"+id ;\n" +
                "        window.location.href=url;\n" +
                "    }\n" +
                "\t/*\n" +
                "\t * 机构信息成功添加返回重新刷新列表\n" +
                "\t */\n" +
                "\tfunction reload(backInfo){\n" +
                "\t\t$.ligerDialog.success(backInfo);\n" +
                "\t\tgrid.loadData(); //重新加载不查询数据库\n" +
                "\t\tm.close();\n" +
                "\t}\n" +
                "\n" +
                "\t/*\n" +
                "\t *删除选中的文章信息\n" +
                "\t */\n" +
                "    function del(id){\n" +
                "        if($.ligerDialog.confirm('确实要删除吗',\n" +
                "                function (yes) {\n" +
                "                    if(yes){\n" +
                "                        var url=\"../"+controlMapper+"/delete.shtml\";\n" +
                "                        $.ajax({\n" +
                "                            type : \"post\",\n" +
                "                            url : url,\n" +
                "                            data : {\n" +
                "                                \"id\" : id\n" +
                "                            },\n" +
                "                            success : function(data) {\n" +
                "                                //如果删除成功，则刷新页面！\n" +
                "                                if(data[\"message\"]==\"1\") {\n" +
                "                                    $.ligerDialog.success(\"删除成功！\");\n" +
                "                                }else if(data[\"mssage\"]==\"0\")  {\n" +
                "                                    $.ligerDialog.error(\"删除失败！\");\n" +
                "                                }else{\n" +
                "                                    $.ligerDialog.error(data[\"mssage\"]);\n" +
                "                                }\n" +
                "                                //删除用户信息后查询初始化\n" +
                "                                grid.loadData(); //重新加载不查询数据库\n" +
                "                            },\n" +
                "                            error : function() {\n" +
                "                                $.ligerDialog.error(\"删除失败！\");\n" +
                "                            }\n" +
                "                        });\n" +
                "                    }\n" +
                "                }));\n" +
                "\n" +
                "    }\n" +
                "\n" +
                "\n" +
                "\n";
                content+="   //搜索\n" +
                        "    function doSearch(){\n" +
                        "        var queryParam=$(\"#queryForm\").serialize();\n" +
                        "        var url = \"../"+controlMapper+"/findAllList.shtml?\"+queryParam;\n" +
                        "        findProjectInfoList(url);\n" +
                        "    }";
        return content;
    }
}
